package com.example.elmspringboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.elmspringboot.controller.utils.BusinessDTO;
import com.example.elmspringboot.controller.utils.Result;
import com.example.elmspringboot.controller.utils.UserDTO;
import com.example.elmspringboot.domain.Business;
import com.example.elmspringboot.domain.User;
import com.example.elmspringboot.security.Jwt.JwtToken;
import com.example.elmspringboot.security.Jwt.JwtUtil;
import com.example.elmspringboot.service.BusinessService;
import com.example.elmspringboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping("/api/login")
public class LoginController {
    @Resource
    private UserService userService;
    @Resource
    private BusinessService businessService;
    @PostMapping
    public Result login(String username, String password){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("name", username);
        User user = userService.getOne(userQueryWrapper);
        if(user!=null && Objects.equals(user.getPassword(), password)){
            String usernamePasswordToken = JwtUtil.sign(username,password);
            SecurityUtils.getSubject().login(new JwtToken(usernamePasswordToken));
            return new Result(true, new UserDTO(usernamePasswordToken, user));
        }
        if(user == null){
            QueryWrapper<Business> businessQueryWrapper = new QueryWrapper<>();
            businessQueryWrapper.eq("name", username);
            Business business = businessService.getOne(businessQueryWrapper);
            if(business!=null && Objects.equals(business.getPassword(), password)){
                String usernamePasswordToken = JwtUtil.sign(username,password);
                SecurityUtils.getSubject().login(new JwtToken(usernamePasswordToken));
                return new Result(true, new BusinessDTO(usernamePasswordToken, business));
            }
            else {
                return new Result(false, null, "账号或密码错误");
            }
        }
        return new Result(false, null, "账号或密码错误");

    }
}
